package com.ruoyi.web.controller.system;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.math.MathUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.github.therapi.runtimejavadoc.repack.com.eclipsesource.json.Json;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.system.service.ISysDeptService;
import lombok.RequiredArgsConstructor;
import org.apache.ibatis.annotations.Param;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * api
 *
 * @author Lion Li
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/Client/v1")
public class ApiController extends BaseController {

    private final ISysDeptService deptService;

    /**
     * 插入订单
     */
    @SaIgnore
    public R<JSONObject> addJSON(@RequestBody JSONObject json) {

        //调用PHP接口获取订单号和二维码
        String orderNo = IdUtil.fastSimpleUUID();
        Double amount = json.getDouble("Amount");
        String invName = json.getStr("invName");



        String token = ServletUtils.getRequest().getHeader("Authorization");
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("Product_id", orderNo);
        paramMap.put("Amount", MathUtil.yuanToCent(amount));
        paramMap.put("Transaction_description", invName);



        String url = "http://yun.aiopms.cn/Demo/fusion/native.php";
        String s = HttpUtil.get(url, paramMap, 5000);
        String qrurl = StrUtil.subBetween(s, "<code_url><![CDATA[", "]]></code_url>");
        //点击结算我会向你的服务发送一条请求，你会得到本次支付所结算的商品，然后你向订单数据库插入本次支付的数据，同时生成订单码等操作后请求php获取支付二维码，然后将二维码和订单码返回前端，我收到后去轮询支付结果，同时你的服务也轮询支付结果，一旦支付就改变支付状态
        JSONObject js = new JSONObject();
        js.set("orderNo", orderNo);
        js.set("url", qrurl);
        //解密jwt
        final JWT jwt = JWTUtil.parseToken(StrUtil.removePrefix(token, "Bearer "));
        JSONObject userInfo = JSONUtil.toBean(jwt.getPayload().getClaimsJson(), JSONObject.class);



        JSONObject o = new JSONObject();
        o.set("UserName", userInfo.getStr("UserName"));
        o.set("Password", userInfo.getStr("Password"));

        List list = new ArrayList<>();
        JSONArray o2 = json.getJSONArray("List");

        list.add(o2);

        JSONObject o3 = new JSONObject();
        o3.set("Confirm", o);
        o3.set("List", list);
        //调用存储过程插入数据库

        deptService.add(o3.toString());

        return R.ok(js);
    }

    @GetMapping("/get")
    @SaIgnore
    public R<String> addAdmin(String orderNo) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("out_trade_no", orderNo);
        String url = "http://yun.aiopms.cn/Demo/fusion/orderquery.php";
        String s = HttpUtil.get(url, paramMap, 5000);
        return R.ok(s);
    }

    @PostMapping("/addOrModifyUser")
//    @Scheduled(cron ="*/20 * * * * ?")
    @SaIgnore
    public R<String> add36() {

        return R.ok(deptService.select1());
    }


    @PostMapping("/addOrUpdateExternalUser")
//    @Scheduled(cron ="*/30 * * * * ?")
    @SaIgnore
    public R<String> add37() {
        return R.ok(deptService.addOrUpdateExternalUser());
    }

    @PostMapping("/addOrUpdatePosition")
//    @Scheduled(cron ="*/20 * * * * ?")
    @SaIgnore
    public R<String> add38() {
        return R.ok(deptService.selectHrPositionTemps());
    }

    //推
    @PostMapping("/addGlOrUpdateOrganization")
//    @Scheduled(cron ="*/20 * * * * ?")
    @SaIgnore
    public R<String>addGlOrUpdateOrganization(){
        return R.ok(deptService.addGlOrUpdateOrganization());
    }

    @GetMapping("/Authorize")
    @SaIgnore
    public String token(@RequestParam("code") String code, @RequestParam("state") String state) {
//        return R.ok("登录成功",deptService.token(code));
        return deptService.token(code, state);
    }

    /**
     * 给前端调用的，也就是推送对方的数据，参数根据前端要求自己定义
     */
    @GetMapping("/Customer")
//    @Scheduled(cron ="*/30 * * * * ?")
    @SaIgnore
    public R<String> client() {

//        return R.ok("登录成功",deptService.token(code));

        deptService.client();

//        deptService.updateErpMdg(Code);


//
//        String CompleteTime = (String) map.get("CompleteTime");
//        String Code = (String) map.get("Code");
//        deptService.updateErpMdgCustomerUpload(map);
        return R.ok();
    }




    /**
     * 对方的回调
     */
    @PostMapping("/Supplier/update")
    @SaIgnore
    public R<String> clientCallBack(@RequestBody JSONObject map, @Param("Supplier") String Supplier,@Param("TaxId")String TaxId,@Param("Active")String Active,@Param("InsertTime")String InsertTime,@Param("MDG")String MDG,@Param("Mail")String Mail,@Param("Phone")String Phone,@Param("Address")String Address,@Param("Contact")String Contact) {
        JSONArray jsonArr = map.getJSONArray("REQUESTINFO");

        for (int i = 0; i < jsonArr.size(); i++) {
            JSONObject jsonObject = jsonArr.getJSONObject(i);
            String ZZSTCEG = jsonObject.getStr("ZZSTCEG");
            String LIFNR = jsonObject.getStr("LIFNR");

            String ZSCRKSJ = jsonObject.getStr("ZSCRKSJ");
//            System.out.println(ZSCRKSJ);
            String NAME_ORG1 = jsonObject.getStr("NAME_ORG1");
            String ZQYYX = jsonObject.getStr("ZQYYX");
            String PHONE = jsonObject.getStr("PHONE");
            String ADRNR = jsonObject.getStr("ADRNR");
            String ZZFR = jsonObject.getStr("ZZFR");


            int result = deptService.getByClientCallBackBo(ZZSTCEG);

            if (result > 0) {
                int re = deptService.updateSySupplier(LIFNR, ZZSTCEG);
                if (re > 0) {
                    return R.ok();
                }
                return R.fail("操作失败","400");
            } else {
                int i1 = deptService.insertSySupplier(NAME_ORG1,ZZSTCEG,Active,ZSCRKSJ,LIFNR,ZQYYX,PHONE,ADRNR,ZZFR);
                if (i1 > 0) {
                    return R.ok();
                }
                return R.fail("操作失败","400");
            }

        }
        return R.ok();
    }

    @PostMapping("/selectMDG")
    @SaIgnore
    public String v1(){
         String s = deptService.selectMDG();
         return JSONUtil.toJsonStr(s);
    }



}
